package com.snail.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.snail.exception.BizException;
//import com.snail.model.dto.user.BindAndLoginDTO;
import com.snail.model.dto.user.BindAndLoginDTO;
import com.snail.model.dto.user.ThirdLoginDTO;
import com.snail.model.pojo.user.SysUser;
import com.snail.model.pojo.user.SysUserTag;
import com.snail.model.vo.user.LoginVO;
import com.snail.model.vo.user.ThirdPartyUserInfoVO;
import com.snail.result.Result;
import com.snail.result.ResultCode;
import com.snail.service.*;
import com.snail.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 蔡徐坤
 * @Date 2025/8/15 10:45
 * @Description: 模拟OAuth2.0授权流程
 */
@Slf4j
@RestController
@RequestMapping("/oauth2")
@RequiredArgsConstructor
public class SysOAuth2Controller {

    private final ThirdPartyAuthService thirdPartyAuthService;

    private final SysUserTagService sysUserTagService;

    /**
     * 第三方回调携带 code，后端负责：换取用户信息 → 查绑定
     * - 已绑定：直接登录并返回 token
     * - 未绑定：返回 needBind=true，前端再调 /oauth2/bind 完成注册绑定
     */
    @PostMapping("/login")
    public Result<LoginVO> loginByThird(@RequestParam String provider,
                                        @RequestParam String code) {
        try {
            LoginVO vo = thirdPartyAuthService.loginByThird(provider, code);
            log.info("loginByThird success, provider={}, code={}, userInfo={}", provider, code, vo.toString());
            return Result.success(vo);
        } catch (RuntimeException e) {
            // 如果异常表示未绑定第三方账号
            if ("UNBOUND_THIRD_PARTY".equals(e.getMessage())) {
                LoginVO vo = new LoginVO();
                vo.setNeedBind(true);       // 表示前端需要跳转绑定页面
                vo.setProvider(provider);   // 第三方平台
                vo.setCode(code);// 第三方 code
                return Result.success(vo);
            }
            // 其他异常
            return Result.failed( e.getMessage());
        }
    }

    /**
     * 未绑定时，前端调用本接口完成：注册本地用户 + 绑定第三方 + 登录
     * 参数仍然是 provider + code（后端会再次向第三方换取用户信息，避免前端伪造）
     */
    @PostMapping("/bind")
    public Result<LoginVO> bindAndLogin(@RequestBody BindAndLoginDTO dto) {
        try {
            LoginVO vo = thirdPartyAuthService.bindAndLogin(dto);
            log.info("bindAndLogin success, bindAndLoginDTO={}, userInfo={}", dto.toString(), vo.toString());
            return Result.success(vo);
        } catch (BizException e) {
            return Result.failed(ResultCode.CLIENT_AUTHENTICATION_FAILED, e.getMessage());
        }
    }
}
